package com.x.uikit.router;

import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.x.uikit.UIKit;
import com.x.uikit.UIKitImpl;

import java.util.Set;

public class XNavigator {
    @NonNull
    XRoute mRoute;
    Bundle mArgument;

    private XNavigator(@NonNull XRoute route) {
        mRoute = route;
    }

    public static XNavigator with(@NonNull String path) {
        XRoute route = XRoute.obtain(path);
        return new XNavigator(route);
    }

    private void ensureArgument() {
        if (mArgument == null) {
            mArgument = new Bundle();
        }
    }

    public XNavigator setArgument(Bundle bundle) {
        ensureArgument();
        mArgument.putAll(bundle);
        return this;
    }

    public XNavigator putArgument(String key, String value) {
        ensureArgument();
        mArgument.putString(key, value);
        return this;
    }

    public void navigate() {
        mRoute.argument = mArgument;
        UIKitImpl.navigate(UIKit.get().getImpl().getAppContext(),mRoute);
    }

    public static void navigate(String url) {
        navigate(Uri.parse(url));
    }

    public static void navigate(Uri uri) {
        String path = uri.toString();
        Bundle bundle = new Bundle();
        Set<String> paramsKeys = uri.getQueryParameterNames();
        if (paramsKeys != null && paramsKeys.size() > 0) {
            for (String key : paramsKeys) {
                String value = uri.getQueryParameter(key);
                bundle.putString(key, TextUtils.isEmpty(value) ? "" : value);
            }
        }
        with(path).setArgument(bundle).navigate();

    }

}
